﻿using BrnMall.Core;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using BrnMall.Core.Domain.Distribution;

namespace BrnMall.RDBSStrategy.SqlServer
{
	/// <summary>
	/// SqlServer策略之分部分部类
	/// </summary>
	public partial class RDBSStrategy : IRDBSStrategy
	{
		#region 分销参数设置

		/// <summary>
		/// 保存分销参数
		/// </summary>
		/// <param name="info">分销参数</param>
		public void SaveDistributionParam(DistributionParamInfo info)
		{
			var key = TypeHelper.ObjectToInt(RDBSHelper.ExecuteScalar(CommandType.Text, string.Format("select top 1 * from [{0}distributionparam]", RDBSHelper.RDBSTablePre)), 0);

			if (key == 0)
			{
				InsertDistributionParam(info);
			}
			else
			{
				UpdateDistributionParam(info, key);
			}
		}
		private void InsertDistributionParam(DistributionParamInfo info)
		{
			var levelPercentStr = info.LevelPercent.Aggregate(string.Empty, (current, item) => current + (item.Item1 + ":" + item.Item2 + ";"));
			var sql = new StringBuilder();
			DbParameter[] param ={
				GenerateInParam("@totallevel", SqlDbType.Int, 4, info.TotalLevel),
				GenerateInParam("@levelpercent", SqlDbType.VarChar, 100, levelPercentStr),
				GenerateInParam("@productpumpedtype", SqlDbType.Int, 4, info.ProductPumpedType),
				GenerateInParam("@productpumpedvalue", SqlDbType.Decimal, 9, info.ProductPumpedValue),
			};
			sql.AppendFormat("insert into [{0}distributionparam]", RDBSHelper.RDBSTablePre);
			sql.Append("([totallevel],[levelpercent],[productpumpedtype],[productpumpedvalue])");
			sql.Append(" values(@totallevel,@levelpercent,@productpumpedtype,@productpumpedvalue)");

			RDBSHelper.ExecuteNonQuery(CommandType.Text, sql.ToString(), param);
		}
		private void UpdateDistributionParam(DistributionParamInfo info, int key)
		{
			var levelPercentStr = info.LevelPercent.Aggregate(string.Empty, (current, item) => current + (item.Item1 + ":" + item.Item2 + ";"));
			var sql = new StringBuilder();
			DbParameter[] param ={
				GenerateInParam("@totallevel", SqlDbType.Int, 4, info.TotalLevel),
				GenerateInParam("@levelpercent", SqlDbType.VarChar, 100, levelPercentStr),
				GenerateInParam("@productpumpedtype", SqlDbType.Int, 4, info.ProductPumpedType),
				GenerateInParam("@productpumpedvalue", SqlDbType.Decimal, 9, info.ProductPumpedValue),
				GenerateInParam("@distributionid", SqlDbType.Decimal, 9, key)
			};
			sql.AppendFormat("update [{0}distributionparam]", RDBSHelper.RDBSTablePre);
			sql.Append(" set [totallevel]=@totallevel");
			sql.Append(",[levelpercent]=@levelpercent");
			sql.Append(",[productpumpedtype]=@productpumpedtype");
			sql.Append(",[productpumpedvalue]=@productpumpedvalue");
			sql.Append(" where [distributionid]=@distributionid");

			RDBSHelper.ExecuteNonQuery(CommandType.Text, sql.ToString(), param);
		}
		/// <summary>
		/// 获取分销参数
		/// </summary>
		/// <returns></returns>
		public IDataReader GetDistributionParam()
		{
			return RDBSHelper.ExecuteReader(CommandType.Text, string.Format("select top 1 * from [{0}distributionparam]", RDBSHelper.RDBSTablePre));
		}

		#endregion

		#region 分销商品设置

		public DataTable GetDistributionProductSetList(int pageSize, int pageNumber, string condition, string sort, out long total)
		{
			condition = string.IsNullOrWhiteSpace(condition) ? condition : "where " + condition;
			sort = string.IsNullOrWhiteSpace(sort) ? sort : "order by " + sort;
			var totalSql = "select count(0) from [{0}products] {1}";
			var listSql = @"SELECT * FROM (
SELECT ROW_NUMBER() OVER(ORDER BY a.pid) AS row,a.pid AS productid,a.name as productname,a.costprice,a.shopprice,a.displayorder,b.id,b.pumpedtype,b.pumpedvalue FROM [{0}products] AS a
LEFT JOIN [{0}distributionproductset] AS b ON a.pid=b.productid
{1}) AS temp
WHERE row>@start AND row <=@end
{2}";
			total =
				Convert.ToInt64(RDBSHelper.ExecuteScalar(CommandType.Text,
					string.Format(totalSql, RDBSHelper.RDBSTablePre, condition)));
			return
				RDBSHelper.ExecuteDataset(CommandType.Text, string.Format(listSql, RDBSHelper.RDBSTablePre, condition, sort), new[]
				{
					GenerateInParam("start", SqlDbType.Int, 4, (pageNumber - 1)*pageSize),
					GenerateInParam("end", SqlDbType.Int, 4, pageSize*pageNumber)
				}).Tables[0];
		}

		public void SaveDistributionProductSet(DistributionProductSetInfo info)
		{
			if (info.Id == 0)
			{
				InsertDistributionProductSet(info);
			}
			else
			{
				UpdateDistributionProductSet(info);
			}
		}

		public void DeleteDistributionProductSet(int id)
		{
			var sql = "delete [{0}distributionproductset] where [id]=@id";
			RDBSHelper.ExecuteNonQuery(CommandType.Text, string.Format(sql, RDBSHelper.RDBSTablePre), new[]
			{
				GenerateInParam("id", SqlDbType.Int, 4, id)
			});
		}

		private void InsertDistributionProductSet(DistributionProductSetInfo info)
		{
			var sql=new StringBuilder();
			sql.AppendFormat("insert into [{0}distributionproductset]",RDBSHelper.RDBSTablePre);
			sql.Append("([productid],[pumpedtype],[pumpedvalue])");
			sql.Append("values(@productid,@pumpedtype,@pumpedvalue)");
			var param = new[]
			{
				GenerateInParam("productid",SqlDbType.Int, 4,info.ProductId),
				GenerateInParam("pumpedtype",SqlDbType.Int, 4,info.PumpedType),
				GenerateInParam("pumpedvalue",SqlDbType.Decimal, 9,info.PumpedValue)
			};
			RDBSHelper.ExecuteNonQuery(CommandType.Text, sql.ToString(), param);
		}

		private void UpdateDistributionProductSet(DistributionProductSetInfo info)
		{
			var sql=new StringBuilder();
			sql.AppendFormat("update [{0}distributionproductset] set ",RDBSHelper.RDBSTablePre);
			sql.Append("[productid]=@productid,[pumpedtype]=@pumpedtype,[pumpedvalue]=@pumpedvalue");
			sql.Append(" where [id]=@id");
			var param = new[]
			{
				GenerateInParam("id",SqlDbType.Int,4,info.Id),
				GenerateInParam("productid",SqlDbType.Int, 4,info.ProductId),
				GenerateInParam("pumpedtype",SqlDbType.Int, 4,info.PumpedType),
				GenerateInParam("pumpedvalue",SqlDbType.Decimal, 9,info.PumpedValue)
			};
			RDBSHelper.ExecuteNonQuery(CommandType.Text, sql.ToString(), param);
		}

		#endregion

		#region 分销商管理

		public DataTable GetDistributorList(int pageSize, int pageNumber, string condition, string sort, out long total)
		{
			var totalSql = "SELECT COUNT(0) FROM [{0}distributor]";
			var sql = @"SELECT * FROM(SELECT ROW_NUMBER() OVER(ORDER BY b.id) AS row, b.*,a.username FROM [{0}users] AS a
JOIN [{0}distributor] AS b ON a.uid =b.userid) AS temp
WHERE row>{1} AND row<={2}";

			total =
				TypeHelper.ObjectToInt(RDBSHelper.ExecuteScalar(CommandType.Text, string.Format(totalSql, RDBSHelper.RDBSTablePre)));
			return RDBSHelper.ExecuteDataset(CommandType.Text,
				string.Format(sql, RDBSHelper.RDBSTablePre, (pageNumber - 1)*pageSize, pageSize)).Tables[0];
		}
		public void SaveDistributor(DistributorInfo info) { }

		public void DeleteDistributor(int id) { }

		#endregion
	}
}
